package com.example.timewidget

import android.annotation.SuppressLint
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.drawable.AnimationDrawable
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.os.Messenger
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.LayoutInflater
import android.view.SurfaceControlViewHost
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.timewidget.databinding.ActivityMainBinding
import com.example.timewidget.util.MessegeHelper.Companion.MSG_CLIENT
import com.example.timewidget.util.MessegeHelper.Companion.MSG_SERVER
import com.example.timewidget.util.TimeUtils
import com.example.timewidget.widgets.TimeTextWidgetProvider
import java.lang.ref.WeakReference
import com.example.utils.CommenUtil
import com.example.utils.MessengerUtil
import com.example.utils.MessengerUtil.Companion.MSG_CLIENT_SURFACEPKG


class MainActivity : AppCompatActivity() {
    private val TAG: String = "my ${this::class.java.simpleName}"

    private lateinit var binding: ActivityMainBinding


    private lateinit var animView: ImageView
    private lateinit var animFrame: AnimationDrawable
    private lateinit var view: View

    private var mViewHost: SurfaceControlViewHost? = null
    private var mvhPkg: SurfaceControlViewHost.SurfacePackage? = null
    private var toHostMessenger: Messenger? = null
    private var clientMessenger: Messenger? = null
    private val hostConnection = HostConnection()

    /**
     * 注册一下hostMessenger
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initAnim()
        initWidget()
        bindHostService()
        binding.startBtn.setOnClickListener {
            val msg = Message.obtain()
            msg.what = MessengerUtil.MSG_CLIENT_TEXTCHANGE
            toHostMessenger?.send(msg)

            Log.d(TAG, "handleMessage: 能不能进入这边@")
            val tv_txt = findViewById<TextView>(R.id.text_add)
            tv_txt.text = "${tv_txt.text} 🍊"
        }
        // 创建一个接收服务端消息的handler
        clientMessenger = Messenger(mHandler())
//        val wManager = getSystemService(WINDOW_SERVICE) as WindowManager
//        val dm = DisplayMetrics()
//        wManager.defaultDisplay.getMetrics(dm)
    }

    private fun initAnim() {
        animView = binding.animationView
        animFrame = animView.background as AnimationDrawable
        animFrame.start()
    }

    @SuppressLint("HandlerLeak")
    inner class mHandler() : Handler() {

        @SuppressLint("ClickableViewAccessibility")
        @RequiresApi(Build.VERSION_CODES.R)
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MessengerUtil.MSG_SERVER_SURFACEINFO -> {
                    Log.d(TAG, "handleMessage: 获取surfaceInfo${msg.data}")
                    val bundle = msg.data
                    val displayId = bundle.getInt(MessengerUtil.KEY_HOST_DISPLAYID)
                    val width = bundle.getInt(MessengerUtil.KEY_HOST_WIDTH)
                    val height = bundle.getInt(MessengerUtil.KEY_HOST_HEIGHT)
                    val hostToken = bundle.getBinder(MessengerUtil.KEY_HOST_HOSTOKEN)
                    // 获取surface的信息开始绘制
                    // 开始view以及一些功能
                    val display = getSystemService(DisplayManager::class.java).getDisplay(displayId)

//                    if (mViewHost == null) {
                    mViewHost = SurfaceControlViewHost(this@MainActivity, display, hostToken)
                    view =
                        LayoutInflater.from(this@MainActivity).inflate(R.layout.host_view, null)
                    val animView: ImageView = view.findViewById(R.id.animationView)
                    val animFrame = animView.background as AnimationDrawable
                    animFrame.start()

                    mViewHost?.setView(view, width, height)
                    mvhPkg?.release()
                    mvhPkg = mViewHost?.surfacePackage
                    Log.d(TAG, "这里可以到吗")
//                    }
                    // 把绘制好的pkg丢回去
                    val toHostMsg = Message.obtain()
                    toHostMsg.what = MSG_CLIENT_SURFACEPKG
                    val toHostBd = Bundle()
                    toHostBd.putParcelable(MessengerUtil.KEY_CLIENT_SURFACEPKG, mvhPkg)
                    toHostMsg.data = toHostBd
                    toHostMessenger?.send(toHostMsg)
                }
            }
        }
    }

    private fun initWidget() {
        // 检查是否有Widget实例
        val manager = AppWidgetManager.getInstance(this)
        val componentName = ComponentName(this, TimeTextWidgetProvider::class.java)
        val appWidgetIds = manager.getAppWidgetIds(componentName)

        if (appWidgetIds.size > 0) {
            // 手动触发更新
            val intent = Intent(this, TimeTextWidgetProvider::class.java)
            intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds)
            sendBroadcast(intent)
        }
    }

    override fun onDestroy() {;
        super.onDestroy()
        Log.d(TAG, "onDestroy: 销毁了吗")
        unbindService(hostConnection)
    }

    override fun onPause() {
        super.onPause()
        animFrame.stop()
    }

    override fun onResume() {
        super.onResume()
        animFrame.start()
    }

    @SuppressLint("UnsafeIntentLaunch")
    private fun bindHostService() {
        Log.d(TAG, "bindHostService: 绑定服务开始！")
        intent = Intent(CommenUtil.HOST_SERVICE_ACTION)
        // 指定具体包名，以防action太多
        intent.setPackage(CommenUtil.HOST_PACKAGE)
//        startService(intent)
        val success = bindService(intent, hostConnection, BIND_AUTO_CREATE)
        Log.d(TAG, "bindHostService: 绑定服务是否成功$success！")
    }


    /**
     * 其实使用匿名object也是可以的
     */
    private inner class HostConnection : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName, service: IBinder
        ) {
            Log.d(TAG, "onServiceConnected: 连接上了吗")
            toHostMessenger = Messenger(service)
            // 把包名告诉host
            val packageName = "com.example.timewidget"
            val msg = Message.obtain()
            msg.what = MessengerUtil.MSG_CLIENT_PACKAGE
            val bundle = Bundle()
            bundle.putString(MessengerUtil.KEY_CLIENT_PACKAGE, packageName)
            msg.data = bundle
            // 并指定host回应的messenger
            msg.replyTo = clientMessenger
            // 一键发送
            toHostMessenger?.send(msg)
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected: 断开了！！")
            toHostMessenger = null
        }
    }


}

